package com.ptswitch.material.pages.material;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.slf4j.Logger;

import com.ptswitch.material.model.material.MaterialAttachment;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.MaterialAttachmentService;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.WebUtil;
import com.ptswitch.material.util.security.PermissionUtil;

public class AddAttachment extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private MaterialAttachmentService uploadSer;
    @Property
    private long materialId;
    @Property
    private List<UploadedFile> files;
    @InjectPage
    private ViewMaterial viewMaterial;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object toAddAttachment(long id) {
        checkPermitted(PermissionUtil.MaterialAttachmentUpload);
        materialId = id;
        files = new ArrayList<UploadedFile>();
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return materialId;
    }

    @OnEvent(value = EventConstants.SUCCESS)
    Object addAttachment() {
        checkPermitted(PermissionUtil.MaterialAttachmentUpload);
        List<MaterialAttachment> uploads = WebUtil.upload(files, MaterialAttachment.class);
        for (MaterialAttachment upload : uploads) {
            upload.setOwnerId(materialId);
            upload.setUser(getVisitor());
            uploadSer.save(upload);
            hlog(HlogConstants.addUpload, upload);
        }
        return viewMaterial.withInit(materialId);
    }
}
